package com.itheima.web;


import com.itheima.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;


@RequestMapping("/common")
@RestController
public class CommonController {

    @Value("${uploadPath}")
    private String uploadPath;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {

        String oldName = file.getOriginalFilename();


        String uuid = UUID.randomUUID().toString().replace("-", "");

        String suffix = oldName.substring(oldName.lastIndexOf("."));

        String newName = uuid + suffix;

        File directory = new File(uploadPath);

        if (!directory.exists()) {

            directory.mkdirs();
        }

        File targetFile = new File(directory, newName);

        file.transferTo(targetFile);


        return R.success(newName);


    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse resp) throws IOException {


        File file = new File(uploadPath + name);

        FileInputStream is = new FileInputStream(file);

        ServletOutputStream os = resp.getOutputStream();

        IOUtils.copy(is, os);

        is.close();


    }
}
